package com.boot2.core.utils;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * @author zhangweilin
 * @Description: xxxxx
 * @date 2020/6/11
 */
public class MySimpleDateFormat extends SimpleDateFormat {

    /**
     * 页面端如果不按时间串格式来转换,或者输出json不按时间串格式生成，也可以直接传或转换毫秒
     */
    public static final String dateFormatPatternMillis = "SSS";

    public MySimpleDateFormat() {
    }

    public MySimpleDateFormat(String pattern) {
        super(pattern);
    }

    public MySimpleDateFormat(String pattern, Locale locale) {
        super(pattern, locale);
    }

    public MySimpleDateFormat(String pattern, DateFormatSymbols formatSymbols) {
        super(pattern, formatSymbols);
    }

    /**
     * 新增直接转毫秒
     *
     * @param source
     * @return
     * @throws ParseException
     */
    @Override
    public Date parse(String source) throws ParseException {
        String pattern = toPattern();
        //如果配置了以毫秒转换，就优先以毫秒转换
        if (dateFormatPatternMillis.equals(pattern)) {
            Date date = new Date(Long.parseLong(source));
            if (null != date) {
                return date;
            }
        }
        return super.parse(source);
    }

    /**
     * 新增毫秒生成
     * @param date
     * @return
     */
    public String format2(Date date) {
        String pattern = toPattern();
        //如果配置了以毫秒转换，就优先以毫秒转换
        if (dateFormatPatternMillis.equals(pattern)) {
            return String.valueOf(date.getTime());
        }
        return super.format(date);
    }


}
